package models

type User struct {
	Model
	Username string `json:"username"`
	Password string `json:"password"`
	Telephone string `json:"telephone"`
	Avatar int `json:"avatar"`
	Des string `json:"des"`
}

func Login(telephone, password string) (User, bool) {
	var user User
	db.Where("telephone = ? AND password = ?", telephone, password).First(&user)
	return user, user.ID > 0
}

func GetUserById(id int) User {
	var user User
	db.Where("id = ?").First(&user)
	return user
}

func GetUserByTelephone(telephone string) User {
	var user User
	db.Where("telephone = ?").First(&user)
	return user
}

func GetAllUsers() (users []User) {
	db.Find(&users)
	return
}

func ExistUserByID(id int) bool {
	var user User
	db.Select("id").Where("id = ?", id).First(&user)
	return user.ID > 0
}

func ExistUserByTelephone(telephone string) bool {
	var user User
	db.Select("id").Where("telephone = ?", telephone).First(&user)
	return user.ID > 0
}

func AddUser(username, password, telephone, des string, avatar int) bool {
	db.Create(&User{
		Username: username,
		Password: password,
		Telephone: telephone,
		Avatar: avatar,
		Des: des,
	})
	return true
}

func DeleteUser(id int) bool {
	db.Where("id = ?", id).Delete(&User{})
	return true
}

func UpdateUser(id int, data interface{}) bool {
	db.Model(&User{}).Where("id = ?", id).Updates(data)
	return true
}
